package com.qf.servlet;

import com.qf.entity.User;
import com.qf.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@WebServlet(urlPatterns = "/updateuser")
public class UpdateUserServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收相关的请求参数
        req.setCharacterEncoding("UTF-8");

        //接收参数
        String id = req.getParameter("id");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String birthday = req.getParameter("birthday");
        String[] powers = req.getParameterValues("power");

        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //封装实体类
        User user = new User()
                .setId(Integer.parseInt(id))
                .setUsername(username)
                .setPassword(password)
                .setName(name)
                .setAge(Integer.parseInt(age))
                .setBirthday(date)
                .setPowers(Arrays.asList(powers));

        //调用业务层 进行用户的信息修改
        int result = userService.update(user);
        if (result > 0) {
            //同步的修改session中的用户信息
            req.getSession().setAttribute("login_user", user);
            //修改成功
            resp.sendRedirect("index.jsp");
        } else {
            //修改失败
            resp.sendRedirect("updateuser.jsp?status=1");
        }
    }
}
